<?php

/**
 * Created by PhpStorm.
 * User: lcw-home
 * Date: 2015/11/14
 * Time: 21:57
 */
namespace Common\Lib;
class Auth
{
    public static function getByUserFull($uid=null){
        $gid=0;
        if(null==$uid)
            $gid=getUserAuth('gid');
        else{
            $cache=getCache('User');
            $gid=$cache[$uid]['gid'];
        }
        $gRules=self::getByGroupFull($gid);
        $pRules=M('AuthAccess')->where(array('uid'=>null==$uid?UID:$uid))->select();
        foreach($pRules as $p){
            $gRules[$p['rule']]=$p['val'];
        }
        return $gRules;
    }
    public static function getByUserSelf($uid){
        $auth=M('AuthAccess');
        $rules=$auth->where(array('uid'=>$uid))->select();
        return $rules;
    }
    public static function getByGroupFull($gid){
        static $groupAuthFull;
        if(isset($groupAuthFull[$gid]))
            return $groupAuthFull[$gid];
        $groupAuthFullCache=S('auth_group_full_'.$gid);
        if(false===$groupAuthFullCache){
            //取上级权限
            $group=getAuthGroup($gid);
            $pRules=array();
            if(!0==$group['pid']){
                $pRules=self::getByGroupFull($group['pid']);
            }
            //取本组权限与上级权限合并
            $rules=self::getByGroupSelf($gid);
            $groupAuthFullCache=array_merge($pRules,$rules);
            S('auth_group_full_'.$gid,$groupAuthFullCache);
        }
        $groupAuth[$gid]=$groupAuthFullCache;
        return $groupAuth[$gid];
    }

    public static function getByGroupSelf($gid){
        static $groupAuthSelf;
        if(isset($groupAuthSelf[$gid]))
            return $groupAuthSelf[$gid];
        $groupAuthSelfCache=S('auth_group_self_'.$gid);
        if(false===$groupAuthSelfCache){
            $groupAuthSelfCache=array();
            $rules=M('AuthAccess')->where(array('gid'=>$gid))->select();
            foreach($rules as $rule){
                $groupAuthSelfCache[$rule['rule']]=$rule['val']==0?false:true;
            }
            S('auth_group_self_'.$gid,$groupAuthSelfCache);
        }
        $groupAuthSelf[$gid]=$groupAuthSelfCache;
        return $groupAuthSelf[$gid];
    }


}